<!-- 用户信息 -->
<template>
    <view class="set-userinfo-wrap">
      <uni-forms
        :model="state.model"
        :rules="state.rules"
        labelPosition="left"
        border
        class="form-box"
      >
        <!-- 头像 -->
        <view class="avatar-section">
          <view class="avatar-container">
            <image
              class="avatar-image"
              :src="state.model && state.model.avatar || '/static/images/default-avatar.png'"
              mode="aspectFill"
            />
            <view class="avatar-edit-overlay">
              <!-- #ifdef MP -->
              <tui-button
                type="white"
                plain
                shape="circle"
                height="46rpx"
                width="160rpx"
                open-type="chooseAvatar"
                @chooseavatar="onChooseAvatar"
                class="edit-button-overlay"
              >
                修改
              </tui-button>
              <!-- #endif -->
              <!-- #ifndef MP -->
              <tui-button 
                type="white" 
                plain 
                shape="circle" 
                height="46rpx" 
                width="160rpx"
                @click="onChangeAvatar"
                class="edit-button-overlay">
                修改
              </tui-button>
              <!-- #endif -->
            </view>
          </view>
        </view>
  
        <!-- 表单区域 -->
        <view class="form-section">
          <!-- 昵称 -->
          <view class="form-item">
            <view class="form-label">昵称</view>
            <view class="form-content">
              <input 
                class="form-input" 
                v-model="state.model.nickname" 
                placeholder="设置昵称"
                type="nickname"
              />
              <view class="clear-btn" @tap="clearNickname">
                <text class="clear-icon">×</text>
              </view>
            </view>
          </view>

          <!-- 性别 -->
          <view class="form-item">
            <view class="form-label">性别</view>
            <view class="form-content">
              <radio-group @change="onChangeGender" class="gender-group">
                <label class="gender-option" v-for="item in sexRadioMap" :key="item.value">
                  <radio
                    :value="item.value"
                    color="#ff6b35"
                    :checked="item.value === (state.model && state.model.sex)"
                    class="gender-radio"
                  />
                  <text class="gender-text">{{ item.name }}</text>
                </label>
              </radio-group>
            </view>
          </view>

          <!-- 手机号 -->
          <view class="form-item" @tap="onChangeMobile">
            <view class="form-label">手机号</view>
            <view class="form-content">
              <text class="form-text">{{ userInfo.mobile || '请绑定手机号' }}</text>
              <view class="arrow-icon">
                <text class="arrow">></text>
              </view>
            </view>
          </view>

          <!-- 登录密码 -->
          <view class="form-item" @tap="onSetPassword">
            <view class="form-label">登录密码</view>
            <view class="form-content">
              <text class="form-placeholder">点击修改登录密码</text>
              <view class="arrow-icon">
                <text class="arrow">></text>
              </view>
            </view>
          </view>

          <!-- 地址管理 -->
          <view class="form-item" @tap="goToAddress">
            <view class="form-label">地址管理</view>
            <view class="form-content">
              <text class="form-text">管理收货地址</text>
              <view class="arrow-icon">
                <text class="arrow">></text>
              </view>
            </view>
          </view>
        </view>
      </uni-forms>
  
      <!-- 第三方账号绑定 -->
      <!-- <view class="third-party-section">
        <view class="section-title">第三方账号绑定</view>
        <view class="account-list">
          <view class="platform-info">
            <view class="platform-icon">微</view>
            <text class="platform-name">微信小程序</text>
          </view>
          <view class="bind-box">
            <view class="info" v-if="state.thirdInfo && state.thirdInfo.openid">
              <image class="avatar" :src="state.thirdInfo.avatar" />
              <text class="name">{{ state.thirdInfo.nickname }}</text>
            </view>
            <button 
              v-if="state.thirdInfo && state.thirdInfo.openid"
              class="relieve-btn"
              @tap="unBindThirdOauth"
            >
              解绑
            </button>
            <button 
              v-else 
              class="bind-btn"
              @tap="bindThirdOauth"
            >
              绑定
            </button>
          </view>
        </view>
      </view> -->
  
      <view class="footer-box ss-p-20">
        <tui-button 
          shadow 
          type="danger" 
          height="80rpx" 
          shape="circle"
          width="100%"
          @click="onSubmit">
          保存
        </tui-button>
      </view>
    </view>
  </template>
  
  <script>
  export default {
    data() {
      return {
        state: {
          model: {}, // 个人信息
          rules: {},
          thirdInfo: {}, // 社交用户的信息
        },
        placeholderStyle: 'color:#BBBBBB;font-size:28rpx;line-height:normal',
        sexRadioMap: [
          {
            name: '男',
            value: '1',
          },
          {
            name: '女',
            value: '2',
          },
        ],
        userInfo: {},
        // sheep已移除，使用平台判断替代
        platformName: 'WechatMiniProgram'
      }
    },
    onLoad() {
      this.getUserInfo();
    },
    methods: {
      // 选择性别
      onChangeGender(e) {
        this.state.model.sex = e.detail.value;
      },
  
      // 修改手机号
      onChangeMobile() {
        uni.navigateTo({
          url: '/subPackage1/phoneLogin/phoneLogin'
        });
      },
  
      // 选择微信的头像，进行上传
      onChooseAvatar(e) {
        const tempUrl = e.detail.avatarUrl || '';
        this.uploadAvatar(tempUrl);
      },
  
      // 手动选择头像，进行上传
      onChangeAvatar() {
        uni.chooseImage({
          success: async (chooseImageRes) => {
            const tempUrl = chooseImageRes.tempFilePaths[0];
            await this.uploadAvatar(tempUrl);
          },
        });
      },
  
    // 上传头像文件
    uploadAvatar(tempUrl) {
      if (!tempUrl) {
        return;
      }
      
      uni.showLoading({
        title: '上传中...'
      });
      
      // 使用 uni.uploadFile 上传文件
      uni.uploadFile({
        url: 'https://www.liujianggongyi.site/app-api/infra/file/upload',
        filePath: tempUrl,
        name: 'file',
        header: {
          'Accept': '*/*',
          'tenant-id': '1',
          'Authorization': uni.getStorageSync('userToken') || '25c0c9fc17414c659c9f9c9dd99b067d'
        },
        success: (uploadFileRes) => {
          try {
            const result = JSON.parse(uploadFileRes.data);
            if (result.code === 0) {
              this.state.model.avatar = result.data;
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              });
            } else {
              throw new Error(result.msg || '上传失败');
            }
          } catch (error) {
            console.error('解析上传结果失败:', error);
            uni.showToast({
              title: '头像上传失败',
              icon: 'error'
            });
          }
        },
        fail: (error) => {
          console.error('头像上传失败:', error);
          uni.showToast({
            title: '头像上传失败',
            icon: 'error'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },
  
      // 修改密码
      onSetPassword() {
        uni.navigateTo({
          url: '/pages/login/changePassword'
        });
      },
  
      // 绑定第三方账号
      async bindThirdOauth() {
        try {
          // 模拟微信授权绑定
          const result = await this.mockWechatBind();
          if (result) {
            await this.getUserInfo();
            uni.showToast({
              title: '绑定成功',
              icon: 'success'
            });
          }
        } catch (error) {
          console.error('绑定失败:', error);
          uni.showToast({
            title: '绑定失败',
            icon: 'error'
          });
        }
      },

      // 模拟微信绑定
      async mockWechatBind() {
        return new Promise((resolve) => {
          setTimeout(() => {
            this.state.thirdInfo = {
              openid: 'mock_openid_' + Date.now(),
              avatar: 'https://cdn1.sanyedu.com/default-avatar.png',
              nickname: '微信用户'
            };
            resolve(true);
          }, 1000);
        });
      },
  
      // 解绑第三方账号
      unBindThirdOauth() {
        uni.showModal({
          title: '解绑提醒',
          content: '解绑后您将无法通过微信登录此账号',
          cancelText: '再想想',
          confirmText: '确定',
          success: async (res) => {
            if (!res.confirm) {
              return;
            }
            try {
              // 模拟解绑操作
              this.state.thirdInfo = {
                openid: '',
                avatar: '',
                nickname: ''
              };
              uni.showToast({
                title: '解绑成功',
                icon: 'success'
              });
            } catch (error) {
              console.error('解绑失败:', error);
              uni.showToast({
                title: '解绑失败',
                icon: 'error'
              });
            }
          },
        });
      },
  
      // 保存信息
      async onSubmit() {
        uni.showLoading({
          title: '保存中...'
        });
        
        try {
          // 检查手机号是否有变化
          if (this.state.model.mobile && this.state.model.mobile !== this.userInfo.mobile) {
            uni.showModal({
              title: '提示',
              content: '手机号修改需要通过验证码验证，请点击手机号进行修改',
              showCancel: false,
              confirmText: '知道了'
            });
            return;
          }
          
          // 只更新基本信息（头像、昵称、性别）
          const result = await this.$api.req('/member/user/update', {
            avatar: this.state.model.avatar,
            nickname: this.state.model.nickname,
            sex: this.state.model.sex,
          }, 'PUT', 'JSON', false);
          
          if (result.code === 0) {
            uni.showToast({
              title: '保存成功',
              icon: 'success'
            });
            // 重新获取用户信息并更新全局状态
            await this.getUserInfo();
            // 通知其他页面用户信息已更新
            uni.$emit('userInfoUpdated', this.state.model);
          } else {
            throw new Error(result.msg || '保存失败');
          }
        } catch (error) {
          console.error('保存失败:', error);
          uni.showToast({
            title: error.message || '保存失败',
            icon: 'error'
          });
        } finally {
          uni.hideLoading();
        }
      },
  
    // 清空昵称
    clearNickname() {
      this.state.model.nickname = '';
    },

    // 跳转到地址管理
    goToAddress() {
      uni.navigateTo({
        url: '../address/address'
      });
    },

    // 获得用户信息
    async getUserInfo() {
      try {
        // 个人信息
        const userResult = await this.$api.req('/member/user/get', {}, 'GET', 'JSON', false);
        if (userResult.code === 0) {
          this.userInfo = userResult.data;
          this.state.model = {
            avatar: userResult.data.avatar || '',
            nickname: userResult.data.nickname || '',
            // 性别统一为字符串，避免与单选框的字符串值不匹配
            sex: String((userResult.data && userResult.data.sex) != null ? userResult.data.sex : '1'),
            // 同步手机号到可编辑模型
            mobile: userResult.data.mobile || ''
          };
          
          // 更新全局用户信息到本地存储
          try {
            uni.setStorageSync('userInfo', userResult.data);
            console.log('用户信息已更新到本地存储:', userResult.data);
          } catch (storageError) {
            console.error('更新本地存储失败:', storageError);
          }
        }

        // 获得社交用户的信息
        // #ifndef H5
        if (this.platformName !== 'H5') {
          try {
            // 暂时模拟数据
            this.state.thirdInfo = {
              avatar: '',
              nickname: '',
              openid: ''
            };
          } catch (error) {
            console.error('获取第三方信息失败:', error);
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
    }
  }
  </script>
  
<style scoped>
  .set-userinfo-wrap {
    background: #fff;
    min-height: 100vh;
  }

  /* 头像区域 */
  .avatar-section {
    background: #fff;
    padding: 60rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .avatar-container {
    position: relative;
    width: 160rpx;
    height: 160rpx;
  }

  .avatar-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 80rpx;
  }

  .avatar-edit-overlay {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 160rpx;
    height: 46rpx;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 0 0 80rpx 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .edit-button-overlay {
    background: transparent !important;
    border: none !important;
  }

  /* 表单区域 */
  .form-section {
    background: #fff;
  }

  .form-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    min-height: 100rpx;
  }

  .form-item:last-child {
    border-bottom: none;
  }

  .form-label {
    width: 120rpx;
    font-size: 28rpx;
    color: #333;
    flex-shrink: 0;
  }

  .form-content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .form-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    background: none;
    border: none;
    outline: none;
  }

  .form-text {
    font-size: 28rpx;
    color: #333;
  }

  .form-placeholder {
    font-size: 28rpx;
    color: #999;
  }

  .clear-btn {
    width: 40rpx;
    height: 40rpx;
    background: #f0f0f0;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20rpx;
  }

  .clear-icon {
    font-size: 24rpx;
    color: #999;
  }

  .arrow-icon {
    margin-left: 20rpx;
  }

  .arrow {
    font-size: 24rpx;
    color: #ccc;
  }

  /* 性别选择 */
  .gender-group {
    display: flex;
    align-items: center;
  }

  .gender-option {
    display: flex;
    align-items: center;
    margin-right: 60rpx;
  }

  .gender-radio {
    transform: scale(0.8);
    margin-right: 10rpx;
  }

  .gender-text {
    font-size: 28rpx;
    color: #333;
  }

  /* 第三方绑定区域 */
  .third-party-section {
    background: #fff;
    margin-top: 20rpx;
  }

  .section-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #666666;
    line-height: 100rpx;
    padding-left: 30rpx;
  }

  .account-list {
    background-color: #fff;
    height: 100rpx;
    padding: 0 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .platform-info {
    display: flex;
    align-items: center;
  }

  .platform-icon {
    width: 40rpx;
    height: 40rpx;
    background: linear-gradient(135deg, #07C160, #00D4AA);
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20rpx;
    color: #fff;
    font-weight: bold;
    margin-right: 10rpx;
  }

  .platform-name {
    font-size: 28rpx;
    color: #333333;
  }

  .bind-box {
    width: 100rpx;
    height: 50rpx;
    line-height: normal;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
  }

  .info {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
  }

  .avatar {
    width: 38rpx;
    height: 38rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 10rpx;
  }

  .name {
    font-size: 28rpx;
    font-weight: 400;
    color: #999999;
  }

  .bind-btn {
    width: 100%;
    height: 100%;
    border-radius: 25rpx;
    background: #f4f4f4;
    color: #999999;
    border: none;
    font-size: 24rpx;
  }

  .relieve-btn {
    width: 100%;
    height: 100%;
    border-radius: 25rpx;
    background: rgba(255, 107, 53, 0.1);
    color: #ff6b35;
    border: none;
    font-size: 24rpx;
  }

  /* 底部保存按钮 */
  .footer-box {
    background: #fff;
    padding: 30rpx;
    border-top: 1rpx solid #f0f0f0;
  }

</style>